package com.framework.modules.base.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.framework.common.config.SystemConfigName;
import com.framework.common.utils.QuickHelper;
import com.framework.common.utils.R;
/*import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;*/
import com.framework.modules.sys.entity.SysRegionAreaEntity;
import com.framework.modules.sys.service.SysRegionAreaService;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.internal.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("location")
@Api(tags = "位置服务")
public class LocationController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysRegionAreaService sysRegionAreaService;

    /**
     * 位置查询
     * @param keywords 关键词
     * @return
     */
    @GetMapping("/search")
    @ApiOperation("位置搜索")
    public R search(String keywords) {
        if (StringUtils.isBlank(keywords)) {
            return R.error("参数为null");
        }
        String geoSdkKey=QuickHelper.getConfigString(SystemConfigName.GEO_SDK_KEY);
        ////restapi.amap.com/v3/assistant/inputtips?key=您的key&keywords=杭州&type=&location=&city=&datatype=all
        String url = "http://restapi.amap.com/v3/assistant/inputtips?key={key}&keywords={keywords}&type=&location=&city=&datatype=all"
                .replace("{key}", geoSdkKey)
                .replace("{keywords}", keywords);
        //logger.info(url);
        try {
            OkHttpClient httpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url)
                    .addHeader("custon-header", "Basic ")
                    .build();
            Response res = httpClient.newCall(request).execute();
            String str = res.body().string();
            //logger.info(str);
            JSONObject obj = QuickHelper.json2object(str, JSONObject.class);
            if(obj.containsKey("tips")){
                return R.ok(obj.getJSONArray("tips"));
            }
            //logger.info(QuickHelper.object2json(obj));
            return R.ok(1,"无数据");
        } catch (Exception e) {
            return R.error("获取失败");
        }
    }

    /**
     * 位置查询
     * @param location 坐标位置 经度,纬度 , 示例值：120.071575,30.293114
     * @return
     */
    @GetMapping("/get_address_list")
    @ApiOperation("获取地址列表")
    public R get_address_list(String location){
        if(StringHelper.isNullOrEmptyString(location)){
            location = String.format("%s,%s");
        }
        String geoSdkKey=QuickHelper.getConfigString(SystemConfigName.GEO_SDK_KEY);
        String url = "http://restapi.amap.com/v3/geocode/regeo?key={key}&location={location}&poitype=&radius=1000&extensions=all&batch=false&roadlevel=0"
                .replace("{key}", geoSdkKey)
                .replace("{location}", location);
        logger.info(url);
        try {
            OkHttpClient httpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url)
                    .addHeader("custon-header", "Basic ")
                    .build();
            Response res = httpClient.newCall(request).execute();
            String str = res.body().string();
            logger.info(str);
            JSONObject obj = QuickHelper.json2object(str, JSONObject.class);
            JSONArray array = obj.getJSONObject("regeocode").getJSONArray("pois");
            logger.info(QuickHelper.object2json(obj));
            return R.ok(array);
        }
        catch (Exception e){
            return R.error("获取失败");
        }
    }

    /**
     * 获取省市区列表
     * @param pid 上一级位置id
     * @return
     *  "extName": "密云区",
     *  "id": 110118,//位置id
     *  "name": "密云",
     *  "pid": 1101,
     */
    @GetMapping("/get_region_list")
    @ApiOperation("获取省市区列表")
    public R getRegionList(@RequestParam(defaultValue = "0") Integer pid){
        //只查询 id,pid,name,extName 三个字段
        return R.ok(sysRegionAreaService.selectList(new EntityWrapper<SysRegionAreaEntity>().eq("pid",pid)));
    }

    /**
     * 获取全部省市区列表
     * @return
     *  "extName": "密云区",
     *  "id": 110118,//位置id
     *  "name": "密云",
     *  "pid": 1101,
     */
    @GetMapping("/get_all_region_list")
    @ApiOperation("获取全部省市区列表")
    public R getAllRegionList(){
        //只查询 id,pid,name,extName 三个字段
        return R.ok(sysRegionAreaService.getAllRegionList());
    }

    /**
     * 获取区域详细信息
     * @param id 位置id
     * @return
     */
    @GetMapping("/get_region_item")
    @ApiOperation("获取区域详细信息")
    public R getRegionItem(@RequestParam(defaultValue = "0") Integer id){
        return R.ok(sysRegionAreaService.selectById(id));
    }
}
